#!/usr/bin/env python3

###############################################################################
# Name:        converter.py
# Purpose:     convert old-types IODEBUG config file to *.yamls type for i5-OS.
# Author:      Bright Li
# Modified by:
# Created:     2018-10-24
# Version:     [0.0.2]
# RCS-ID:      $$
# Copyright:   (c) Bright Li
# Licence:
###############################################################################

from data.parser import *
import os.path

class I5osYamlsConverter:
    """ i5os-CNC系统新版配置文件的转换器 """
    LIST_CACHE_CHOICE = []
    LIST_VERSION_CHOICE = []

    def __init__(self):
        # self.iodata = ConfigFileParser()
        self.default_filetype = YamlLoader()
        self.yamls_strategy = I5osYamlConvertStrategy()


    def load_anyfile(self, path: str):
        """ 载入任何文件类型，并将其转换为 [标准数据集] IModelData """
        _, ext = os.path.splitext(path)
        print(ext)
        if ext == ".yamls":
            self.iodata = ConfigFileParser.load_from_file(path, self.default_filetype, self.yamls_strategy)
        elif ext == ".yaml":
            try:
                self.iodata = ConfigFileParser.load_from_file(path, self.default_filetype, MillingYamlConvertStrategy())
            except Exception as e:
                print(e)
                self.iodata = ConfigFileParser.load_from_file(path, self.default_filetype, TurningYamlConvertStrategy())
        else:
            # file_type = INI_Loader()
            raise Exception("转换器目前不支持【ini】文件的读取")
        print("完成数据载入")

    def dump_file(self, path: str):
        ConfigFileParser.save_as_file(path, self.iodata, self.default_filetype, self.yamls_strategy)


def Test_for_ConfigFileParser():
    filetype = YamlLoader()
    output_strategy = I5osYamlConvertStrategy()

    config = ConfigFileParser()
    iodata = config.load_from_file("./data/test/plc_io_i5os.yamls", filetype, I5osYamlConvertStrategy())
    # iodata = config.load_from_file("./data/test/plc_io_milling.yaml", filetype, MillingYamlConvertStrategy())
    # iodata = config.load_from_file("./data/test/plc_io_turning.yaml", filetype, TurningYamlConvertStrategy())
    config.save_as_file("./data/test/export/123.yamls", iodata, filetype, output_strategy)


if __name__ == "__main__":
    # Test_for_ConfigFileParser()

    tool = I5osYamlsConverter()
    tool.load_anyfile("./data/test/plc_io_turning.yaml")  # ("./data/test/plc_io_milling.yaml")  # ("./data/test/plc_io_i5os.yamls")
    tool.dump_file("./data/test/export/123.yamls")
